<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import { defineStore } from "pinia";
import { fetchFunction } from "./fetch";
import HelloWorld from "./components/HelloWorld.vue";
import { initSSRState } from "./libs/ssr";
import { RouterView, useRoute } from "vue-router";

let useAppStore = defineStore("app", {
	state: () => ({
		ssrRendered: false,
		// other...
		package: "",
		myStr: "",
		myStr2: "",
	}),
});

let data = useAppStore();
let route = useRoute();

initSSRState(initStore, initPage, {
	appData: data.$state,
});

// 通常只在服务端初始化时被调用一次
// 不能包含客户端代码
async function initStore() {
	data.myStr = "str1";
	data.myStr2 = "str2";
	let fetchFn = await fetchFunction();
	try {
		console.log("Home initStore");
		data.package = await fetchFn("http://localhost:5173/package.json").then((res: any) => res.text());
	} catch (error) {
		console.log("fetch error", error);
		data.package = "fetch error";
	}
}
async function initPage(clientInitStore: Function) {
	clientInitStore();

	// 第二次调用clientInitStore会触发客户端调用initStore函数
	clientInitStore();

	console.log("Home initPage");
	console.log("package", data.package);
	console.log("str", data.myStr);
	console.log("str", data.myStr2);
	data.myStr = data.package || "newStr";
}
</script>

<template>
	<div>
		<div>package:{{ data.package }}</div>
		<div>myStr:{{ data.myStr }}</div>
		<div>myStr2:{{ data.myStr2 }}</div>
		<a href="https://vitejs.dev" target="_blank">
			<img src="/vite.svg" class="logo" alt="Vite logo" />
		</a>
		<a href="https://vuejs.org/" target="_blank">
			<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
		</a>
	</div>
	<HelloWorld msg="Vite + Vue" />
	{{ route }}
</template>

<style scoped>
.logo {
	height: 6em;
	padding: 1.5em;
	will-change: filter;
}
.logo:hover {
	filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
	filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
